﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using System.Drawing;
using System.Drawing.Imaging;

namespace CaptchaControl
{
    public class CaptchaHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            HttpApplication application = context.ApplicationInstance;

            string guid = application.Request.QueryString["guid"];
            bool useSession = !string.IsNullOrEmpty(application.Request.QueryString["useSession"]); // if empty, don't use session

            if (string.IsNullOrEmpty(guid) == false)
            {
                CaptchaImage captchaImage;

                if (useSession == true)
                {
                    captchaImage = (CaptchaImage)HttpContext.Current.Session[guid];
                }
                else
                {
                    captchaImage = (CaptchaImage)HttpRuntime.Cache.Get(guid);
                }

                Bitmap bitmap = captchaImage.GenerateImage();
                bitmap.Save(application.Context.Response.OutputStream, ImageFormat.Jpeg);
                bitmap.Dispose();
                application.Response.ContentType = "image/jpeg";
                application.Response.StatusCode = 200;
            }
            else
            {
                application.Response.StatusCode = 404;
            }

            context.ApplicationInstance.CompleteRequest();
        }


    }
}
